package handler

import (
	"api/commont"
	"api/internal/request"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	pb "vehicle_management_srv/proto"
)

func VehicleCreate(c *gin.Context) {
	value, _ := c.Get("userId")
	uid := value.(uint)
	json := request.VehicleCreateRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		commont.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	con := pb.NewVehicleClient(client)
	req := &pb.VehicleCreateReq{
		VehicleName:   json.VehicleName,
		VehicleNumber: json.VehicleNumber,
		DriverId:      int64(uid),
		Certified:     int64(json.Certified),
	}
	create, err := con.VehicleCreate(c, req)
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	commont.JsonRes(c, 200, "车辆注册成功", create)
}

func VehicleUpdate(c *gin.Context) {
	json := request.VehicleUpdateRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		commont.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	con := pb.NewVehicleClient(client)
	req := &pb.VehicleUpdateReq{
		VehicleId: int64(json.VehicleId),
		Certified: int64(json.Certified),
	}
	create, err := con.VehicleUpdate(c, req)
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	commont.JsonRes(c, 200, "信息修改成功", create)
}

func VehicleShow(c *gin.Context) {
	json := request.VehicleShowRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		commont.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	con := pb.NewVehicleClient(client)
	req := &pb.VehicleShowReq{
		VehicleId: int64(json.VehicleId),
	}
	create, err := con.VehicleShow(c, req)
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	commont.JsonRes(c, 200, "认证情况展示成功", create)
}
